package com.ihr360.expr.function.excel;

import com.ihr360.expr.ExprDate;
import com.ihr360.expr.ExprDouble;
import com.ihr360.expr.ExprError;
import com.ihr360.expr.ExprException;
import com.ihr360.expr.ExprString;
import com.ihr360.expr.context.IEvaluationContext;
import com.ihr360.expr.core.AbstractFunction;
import com.ihr360.expr.core.Expr;
import com.ihr360.expr.core.ExprEvaluatable;
import com.ihr360.expr.utils.DateUtils;

import java.util.Calendar;
import java.util.Date;


public abstract class AbstractCalendar extends AbstractFunction {
    @Override
    public Expr evaluate(IEvaluationContext context, Expr[] args) throws ExprException {
        assertArgCount(args, 1);
        Expr arg = args[0];
        if (arg instanceof ExprEvaluatable) {
            arg = ((ExprEvaluatable) arg).evaluate(context);
        }
        if (arg instanceof ExprString) {
            String datetime = arg.toString();
            Date date = DateUtils.parse(datetime);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            int value = calendar.get(getField());
            if (getField() == Calendar.MONTH) {
                value = value + 1;
            }
            return new ExprDouble(value);
        }
        if (arg instanceof ExprDate){
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(((ExprDate) arg).date);
            int value = calendar.get(getField());
            if (getField() == Calendar.MONTH) {
                value = value + 1;
            }
            return new ExprDouble(value);
        }
        return ExprError.NA;
    }

    public abstract int getField();
}
